*****************************************************
** code up how many risk factors each state has
****************************************************

** more developed heroin markets prior to 2010
** This is based on the per-capita death rate from heroin
preserve
	use ./heroin_deaths_state_month.dta, clear
	gen yeargroup = year>=2008 & year<=2009 
	egen pop_group = total(population), by(yeargroup fips)
	egen hdeaths_group = total(heroin_deaths), by(yeargroup fips)
	egen hrate_rf1 = max( (yeargroup==1)*(hdeaths_group/pop_group) ), by(fips)
	summ hrate_rf1 if year==2009 & month==1, detail
	local medrate = r(p50)
	local rate75 = r(p75)
	local rate25 = r(p25)
	gen rfact1 = 0
	replace rfact1 = 1 if hrate_rf1>=`rate25'
	replace rfact1 = 2 if hrate_rf1>=`rate75'
        gen rfact1_ge50=hrate_rf1>=`medrate'
	keep if year==2010 & month==1
	keep fips rfact1 rfact1_ge50 hrate_rf1
	sort fips
	tempfile rfact1er
	save `rfact1er'
restore 
sort fips
merge m:1 fips using `rfact1er'
drop _merge

** More use of florida prior to 2010
gen rfact2 = 0
replace rfact2 = 1 if fips==5 | fips==6 | fips==8 | fips==9 | fips==17 | fips==21 | fips==22 ///
| fips==24 | fips==25 | fips==27 | fips==28 | fips==29 | fips==31 | fips==32 | fips==35 ///
| fips==37 | fips==39 | fips==41 | fips==42 | fips==48 | fips==49 | fips==51 ///
| fips==53 | fips==54 | fips==55
replace rfact2 = 2 if fips==1 | fips==2 | fips==13 | fips==18 | fips==19 | fips==23 | fips==26 ///
| fips==33 | fips==34 | fips==36 | fips==44 | fips==47 | fips==50

** Create a measure based on oxycodone shipments per person.
preserve
	use opioids_together.dta, clear
	gen yeargroup = year>=2008 & year<=2009
	egen orate_rf = mean( oxycodone_pc ), by(fips yeargroup)
	egen orate_rf1 = max( (yeargroup==1)*orate_rf ), by(fips)
	summ orate_rf1 if year==2009 & quarter==1, detail
	local medrate = r(p50)
	local rate25 = r(p25)
	local rate75 = r(p75)
	gen rfact7 = 0
	replace rfact7 = 1 if orate_rf1>`rate25'
	replace rfact7 = 2 if orate_rf1>`rate75'
    gen rfact7_ge50=orate_rf1>=`medrate'
	keep if year==2010 & quarter==1
	keep fips rfact7 rfact7_ge50 orate_rf1
	sort fips
	tempfile rfact7er
	save `rfact7er'
restore
sort fips
merge m:1 fips using `rfact7er'
drop _merge

